<template>

  <div class="JNPF-common-layout">

     <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>

          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-input v-model="query.customerName" placeholder="请输入客户名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <div>
<!--            <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增</el-button>-->
<!--            <el-button type="text" icon="el-icon-download" @click="exportData()">导出</el-button>-->
          </div>
          <div class="JNPF-common-head-right">
<!--            <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增</el-button>-->
<!--            <el-button type="text" icon="el-icon-download" @click="exportData()">导出</el-button>-->
            <!-- 添加的下拉菜单 -->
            <el-dropdown  style="margin-right: 50px" >
              <el-button size="small">
                批量操作<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item @click.native="batchConfirm">批量核账</el-dropdown-item>
<!--                <el-dropdown-item @click="batchDelete">批量通知</el-dropdown-item>-->
<!--                <el-dropdown-item @click="batchDelete">开票申请</el-dropdown-item>-->
<!--                <el-dropdown-item @click="batchDelete">批量催款</el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
            <el-tooltip content="高级查询" placement="top" v-if="true">
              <el-link icon="icon-ym icon-ym-filter JNPF-common-head-icon" :underline="false"
                       @click="openSuperQuery()"
              />
            </el-tooltip>
            <el-tooltip effect="dark" :content="$t('common.refresh')" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false"
                       @click="initData()"
              />
            </el-tooltip>
          </div>
        </div>
        <div class="total-bar">
           <span style="margin-left: 50px">  账单总额：<span style="color: orange;margin-left: 10px">￥{{ moneyJson.sumReceivable }}元</span></span>
          <span style="margin-left: 50px">  已收：<span style="color: red;margin-left: 10px">￥{{ moneyJson.sumReceived }}元</span></span>
          <span style="margin-left: 50px">  待收：<span style="color: #00afff;margin-left: 10px">￥{{ moneyJson.sumNotReceived }}元</span></span>
        </div>
        <div class="JNPF-common-layout-main JNPF-flex-main">

          <JNPF-table v-loading="listLoading" :data="list" @sort-change="sortChange" :span-method="arraySpanMethod"
                      has-c @selection-change="handleSelectionChange"
          >
            <el-table-column
              prop="customerName"
              label="客户名称"
              align="left"
            >
              <template slot-scope="scope">
                <a style="color:#00afff"  @click="goDetail(scope.row.id)">{{scope.row.customerName}}</a>
              </template>
            </el-table-column>

<!--            <el-table-column prop="customerName" label="客户名称" align="left"-->
<!--            />-->
            <el-table-column prop="billNo" label="账单编号" align="left"
            />
            <el-table-column prop="contractNo" label="合同号" align="left"
            />

            <el-table-column prop="leaseSpace" label="资产名称" align="left"
            />

            <el-table-column prop="expenseCycleDate" label="计费周期" align="left"
            />
            <el-table-column prop="isReviewBill" label="是否核账" align="left"
            >
            <template slot-scope="scope">
              <span v-if="scope.row.isReviewBill == 1" style="color: green">是</span>
              <span v-if="scope.row.isReviewBill == 0" style="color: red">否</span>

            </template>

            </el-table-column>

            <!--          <el-table-column label="计费周期" prop="contractNo" algin="left"-->
            <!--          >-->
            <!--            <template slot-scope="scope">-->
            <!--             等待计算-->
            <!--            </template>-->
            <!--          </el-table-column>-->


            <el-table-column label="操作" fixed="right"
                             width="150"
            >
              <template slot-scope="scope">
                <el-button type="text"
                           @click="addOrUpdateHandle1(scope.row.id)"
                >变更
                </el-button>
                <el-button type="text"
                           @click="makeSure(scope.row.id)"
                >核账
                </el-button>
<!--                <el-button type="text" class="JNPF-table-delBtn" @click="handleDel(scope.row.id)">删除-->
<!--                </el-button>-->
<!--                <el-button type="text"-->
<!--                           @click="goDetail(scope.row.id)"-->
<!--                >详情-->
<!--                </el-button>-->
              </template>
            </el-table-column>
          </JNPF-table>

          <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
                      @pagination="initData"

          />
        </div>
      </div>
    </div>
    <JNPF-Form v-if="formVisible" ref="JNPFForm" @refresh="refresh"/>
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download"/>
    <Detail   @close="colseFlow" v-if="detailVisible" ref="Detail" @refresh="detailVisible=false"/>

    <FlowBox v-if="flowVisibleLC" ref="FlowBox" @close="colseFlowLC" />


    <SuperQuery v-if="superQueryVisible" ref="SuperQuery" :columnOptions="superQueryJson"
                @superQuery="superQuery"
    />
    <el-dialog title="账单核账"
               :visible.sync="flag" width="800px" class="JNPF-dialog JNPF-dialog_center transfer-dialog" lock-scroll
               append-to-body
               :modal-append-to-body="false" @close="onClose"
    >
      <el-form ref="elForm" :model="dataForm" size="medium" label-width="120px" class="custom-form">
        <el-form-item label="合同编号" class="form-item">
           {{dataForm.contractNo}}
        </el-form-item>
        <el-form-item label="账单周期" class="form-item">
          {{dataForm.expenseCycleDate}}
        </el-form-item>
        <el-form-item label="客户姓名" class="form-item">
          {{dataForm.customerName}}
        </el-form-item>
        <el-table border :data="dataForm.zcbillitemList" size="mini">
          <el-table-column type="index" width="150" label="序号" align="center"/>

          <el-table-column width="100" prop="expenseItem" label="费用项">
            <template slot-scope="scope">
              <p>{{ scope.row.expenseItem }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="expenseItem" width="250" label="本金">
            <template slot-scope="scope">
              <div style="text-align: left" v-html="scope.row.principal"></div>
            </template>
          </el-table-column>
          <el-table-column prop="expenseItem" width="250" label="滞纳金明细">
            <template slot-scope="scope">
              <div style="text-align: left" v-html="scope.row.lateFee"></div>
            </template>
          </el-table-column>

        </el-table>

        <el-form-item class="form-item" style="text-align: center">
          <el-button type="primary" style="width: 150px;margin-top: 20px" @click="makeToSure">确定</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>

<script>
import request from '@/utils/request'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import JNPFForm from './Form'
import ExportBox from './ExportBox'
import { getDataInterfaceRes } from '@/api/systemData/dataInterface'
import Detail from './Detail'
import columnList from './columnList'
import SuperQuery from '@/components/SuperQuery'
import superQueryJson from './superQueryJson'
import FlowBox from '@/views/workFlow/components/FlowBox'
export default {
  components: { JNPFForm, ExportBox, Detail, SuperQuery,FlowBox },
  data() {
    return {
      flag:false,
      dataForm:{},
      zcbillitemList:[],
      moneyJson:{},
      multipleSelection: [],
      expandObj: {},
      columnOptions: [],
      mergeList: [],
      exportList: [],
      columnList,
      flowVisibleLC:false,
      superQueryVisible: false,
      superQueryJson,
      detailVisible: false,
      query: {
        paymentBillNo: undefined
      },
      treeProps: {
        children: 'children',
        label: 'fullName',
        value: 'id'
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        superQueryJson: '',
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      },
      formVisible: false,
      exportBoxVisible: false,
      paymentTypeOptions: [{ 'fullName': '选项一', 'id': '1' }, { 'fullName': '选项二', 'id': '2' }],
      paymentTypeProps: { 'label': 'fullName', 'value': 'id' },
      receiptAccountOptions: [{ 'fullName': '选项一', 'id': '1' }, { 'fullName': '选项二', 'id': '2' }],
      receiptAccountProps: { 'label': 'fullName', 'value': 'id' },
      paymentByOptions: [{ 'fullName': '选项一', 'id': '1' }, { 'fullName': '选项二', 'id': '2' }],
      paymentByProps: { 'label': 'fullName', 'value': 'id' },
      paymentAccountOptions: [{ 'fullName': '选项一', 'id': '1' }, { 'fullName': '选项二', 'id': '2' }],
      paymentAccountProps: { 'label': 'fullName', 'value': 'id' },
      tableField120_expenseItemOptions: []
    }
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || ''
    }
  },
  created() {
    this.getColumnList(),
      this.initData()
      this.getSumMoney()
  },
  methods: {
    makeToSure() {
      // 显示二次确认对话框
      this.$confirm('确定账单没有问题，进行核账?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var data = []
        data.push(this.dataForm.id)
        request({
          url: `/api/zcgl/fico/bill/review`,
          data: data,
          method: 'post'
        }).then(res => {
          this.flag = false
          this.$message({
            type:'success',
            message: res.msg,
            onClose: () => {
              this.initData()
            }
          })
        })
      }).catch(() => {
        // 用户取消操作时的处理逻辑，这里可以不做任何处理
      });
    },
    onClose(){
      this.flag = false
    },
    colseFlowLC(){

      this.flowVisibleLC = false
    },

    colseFlow(){

      this.detailVisible = false
    },

    batchConfirm(){


      request({
        url: `/api/zcgl/fico/bill/review`,
        data:this.multipleSelection,
        method: 'post'
      }).then(res => {
        this.$message({
          type: 'success',
          message: res.msg,
          onClose: () => {
            this.initData()
          }
        })
      })
        this.initData()

    },
    getSumMoney(){

      request({
        url: `/api/zcgl/fico/bill/getSumMoney`,
        method: 'get'
      }).then(res => {
        this.moneyJson = res.data
      })
    },

    handleSelectionChange(val) {
      const res = val.map(item => item.id)
      this.multipleSelection = res
    },
    getColumnList() {
      // 没有开启权限
      this.columnOptions = this.transformColumnList(this.columnList)
    },
    transformColumnList(columnList) {
      let list = []
      for (let i = 0; i < columnList.length; i++) {
        const e = columnList[i]
        if (!e.prop.includes('-')) {
          list.push(e)
        } else {
          let prop = e.prop.split('-')[0]
          let label = e.label.split('-')[0]
          let vModel = e.prop.split('-')[1]
          let newItem = {
            align: 'center',
            jnpfKey: 'table',
            prop,
            label,
            children: []
          }
          e.vModel = vModel
          if (!this.expandObj.hasOwnProperty(`${prop}Expand`)) this.$set(this.expandObj, `${prop}Expand`, false)
          if (!list.some(o => o.prop === prop)) list.push(newItem)
          for (let i = 0; i < list.length; i++) {
            if (list[i].prop === prop) {
              list[i].children.push(e)
              break
            }
          }
        }
      }
      this.getMergeList(list)
      this.getExportList(list)
      return list
    },
    arraySpanMethod({ column }) {
      for (let i = 0; i < this.mergeList.length; i++) {
        if (column.property == this.mergeList[i].prop) {
          return [this.mergeList[i].rowspan, this.mergeList[i].colspan]
        }
      }
    },
    getMergeList(list) {
      let newList = JSON.parse(JSON.stringify(list))
      newList.forEach(item => {
        if (item.children && item.children.length) {
          let child = {
            prop: item.prop + '-child-first'
          }
          item.children.unshift(child)
        }
      })
      newList.forEach(item => {
        if (item.children && item.children.length) {
          item.children.forEach((child, index) => {
            if (index == 0) {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 1,
                colspan: item.children.length
              })
            } else {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 0,
                colspan: 0
              })
            }
          })
        } else {
          this.mergeList.push({
            prop: item.prop,
            rowspan: 1,
            colspan: 1
          })
        }
      })
    },
    getExportList(list) {
      let exportList = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].jnpfKey === 'table') {
          for (let j = 0; j < list[i].children.length; j++) {
            exportList.push(list[i].children[j])
          }
        } else {
          exportList.push(list[i])
        }
      }
      this.exportList = exportList
    },
    goDetail(id) {

      this.detailVisible= true

      // this.detailVisible = true
      // this.$router.push(`/zcgl/zcglcwbill/Detail?id=${id}`)
      // this.$router.push(`/zcglcwbilldetail?id=${id}`)
      //修改为页面跳转
      this.$nextTick(() => {
        this.$refs.Detail.init(id)
      })
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
      this.listQuery.sidx = !order ? '' : prop
      this.initData()
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query,
        keyword: this.keyword,
        dataType: 0,
        menuId: this.menuId
      }
      request({
        url: `/api/zcgl/fico/bill/getList`,
        method: 'post',
        data: _query
      }).then(res => {
        var _list = []
        for (let i = 0; i < res.data.list.length; i++) {
          let _data = res.data.list[i]
          _list.push(_data)
        }
        this.list = _list.map(o => ({
          ...o,
          ...this.expandObj
        }))
        console.log(this.list[0])

        this.total = res.data.pagination.total
        this.listLoading = false
        this.$forceUpdate()

      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        request({
          url: `/api/example/ZcglCwBill/${id}`,
          method: 'DELETE'
        }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            onClose: () => {
              this.initData()
            }
          })
        })
      }).catch(() => {
      })
    },
    openSuperQuery() {
      this.superQueryVisible = true
      this.$nextTick(() => {
        this.$refs.SuperQuery.init()
      })
    },
    superQuery(queryJson) {
      this.listQuery.superQueryJson = queryJson
      this.listQuery.currentPage = 1
      this.initData()
    },
    makeSure(id){
     this.flag= true
      request({
        url: '/api/zcgl/fico/bill/getBillInfo/' + id,
        method: 'get'
      }).then(res => {
      this.dataForm = res.data
      })




    },

    addOrUpdateHandle1(id,flowState){
      // let data = {
      //   id: id || '',
      //   enCode: 'zcbg',
      //   flowId:'624930574271784645',
      //   // flowId:'624934757007894213',
      //   formType: 1,
      //   opType: flowState ? 0 : '-1',
      //   status: flowState
      // }
      // this.flowVisibleLC = true
      // this.$nextTick(() => {
      //
      //   this.$refs.FlowBox.init(data)
      let data = {
        id: id || '',
        enCode: 'bgjl',
        flowId:'636523805551900741',
        // flowId:'624934757007894213',
        formType: 1,
        opType: flowState ? 0 : '-1',
        status: flowState
      }
      this.flowVisibleLC = true
      this.$nextTick(() => {

        this.$refs.FlowBox.init(data)
      })
    },
    addOrUpdateHandle(id, isDetail) {

      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.JNPFForm.init(id, isDetail)
      })
    },
    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.exportList)
      })
    },
    download(data) {
      let query = { ...data, ...this.listQuery, ...this.query, menuId: this.menuId }
      request({
        url: `/api/example/ZcglCwBill/Actions/Export`,
        method: 'post',
        data: query
      }).then(res => {
        if (!res.data.url) return
        this.jnpf.downloadFile(res.data.url)
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery.currentPage = 1
      this.listQuery.pageSize = 20
      this.listQuery.sort = 'desc'
      this.listQuery.sidx = ''
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.search()
    }
  }
}
</script>
<style>
.total-bar {
  /*width: 98%;*/
  height: 40px;
  border: 1px solid #91d5ff;
  background-color:#e6f7ff;
  opacity: 0.8;
  display: flex;
  align-items: center;
  /*justify-content: center;*/
  padding: 8px 15px;
  margin-bottom: 15px;
  border-radius: 5px;
  font-size: 14px; /* 调整字体大小 */
  color: #333; /* 字体颜色 */
}

</style>
